<?php

Yii::import('Cms.components.widgets.BaseFormWidget');

class GenericForm extends BaseFormWidget {

    public function run() {
        if ($this->SelectedLayout == null) {
            Yii::import($this->contentType->model, true);

            list($module, $tmp, $className) = explode('.', $this->contentType->model);
            $servicePath = "{$module}.{$className}.";
            $viewPath = $module . '.views.admin.' . lcfirst($className) . '._form';
            $formId = trim(strtolower(str_replace('_', '-', preg_replace('/(?<![A-Z])[A-Z]/', '-\0', $className))), '-');

            if (Yii::app()->request->IsPostRequest) {
                // save posted data
                $_POST['validateOnly'] = ($this->controller->post('ajax', '') == $formId);
                $result = FSM::run($servicePath . 'save', $_POST);
                $model = $result->model;

                if ($this->controller->post('ajax', '') == $formId) {
                    echo $result->getActiveErrorMessages($result->model);
                    Yii::app()->end();
                }
                if (!$result->hasErrors()) {
                    $form = Form::model()->find("content_id = {$this->contentType->id}");

                    // send email notifcation
                    if (trim($form->email) != '') {
                        // allow to send to multiple emails user entered in form builder
                        $emails = explode("\n",$form->email);
                        foreach ($emails as $email) {
                            quickMail($email, 'Cms.views.widgets.genericForm.form_submitted', array('model' => $model));
                        }
                    }

                    // redirect or show message or use CORE standard message
                    if ($form->redirect != '')
                        $this->controller->redirect($form->redirect);
                    elseif (trim($form->success_message) != '')
                        return $form->success_message;
                    else
                        $this->controller->message = 'Your submission has been saved!';
                }
            } else {
                // show edit form
                $model = new $className;
            }

            cs()->registerCssFile(themeUrl() . '/styles/form.css');
            return $this->render($viewPath, array('model' => $model), true);
        } else {
            return $this->SelectedLayout->render();
        }
    }

}